package jt.classic.app.hys.hysyd;


import jt.classic.system.ISystem;
import jt.classic.system.SimpleAction;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.user.IUser;

import org.limp.basework.console.XSystemConsole;
import org.limp.basework.console.XSystemConsoleRunException;
import org.limp.basework.impl.CommonBean4HSQ;

import org.limp.mine.Controller;
import org.limp.mine.DateTrimmer;
import org.limp.mine.Label;
import org.limp.mine.QueryJack;
import org.limp.mine.QueryJackFactory;
import org.limp.mine.StringTool;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import java.sql.Connection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class HysydAction extends SimpleAction {
    /**
    * 会议室预定列表
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    * @throws Exception
    */
    public ActionForward list(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        Map param = req.getResource();

        String pageNO = StringTool.checkString(param.get("pageNO"));

        /*会议室名称*/
        String hname = StringTool.toUTF8String(StringTool.checkString(
                    request.getParameter("hname")));

        /*申请日期*/
        String hdate = StringTool.checkString(request.getParameter("hdate"));

        hdate = DateTrimmer.formatDateForVarchar(hdate);

        IUser user = ISystem.getSessionUser(request);

        String sqlwhere = "";

        if (ISystem.matchrole(user, "hysadmin")) {
            if (user.igroup() != null) {
                sqlwhere += (" AND b.HYS_GSID_NAME = '" +
                user.igroup().ibranchgroup(0) + "' ");
            }
        } else if (ISystem.matchrole(user, "admin")) {
            //do nothing
        } else {
            sqlwhere += (" AND a.CREATE_USER = '" + user.id()+"'");
        }

        if (!hname.equals("")) {
            sqlwhere += (" AND b.HYS_MC LIKE '%" + hname + "%'");
        }

        if (!hdate.equals("")) {
            sqlwhere += (" AND a.CREATE_DATE LIKE '%" + hdate + "%'");
        }

        request.setAttribute("hname", hname);
        request.setAttribute("hdate", DateTrimmer.getYMD_S_LBL(hdate));

        String sql2 =
            "SELECT a.*,b.HYS_MC,b.HYS_ID,c.NAME ,c.ID FROM APP_H_HYSYD a inner join APP_H_HYSZY b on a.HYSYD_HYSID = b.HYS_ID inner join ISYS_USER c on c.ID = a.CREATE_USER " +
            sqlwhere + " ORDER BY a.HYSYD_KSSJ DESC";
        String sql1 = "SELECT COUNT(*) FROM (" +
            "SELECT a.*,b.HYS_MC,b.HYS_ID,c.NAME ,c.ID FROM APP_H_HYSYD a inner join APP_H_HYSZY b on a.HYSYD_HYSID = b.HYS_ID inner join ISYS_USER c on c.ID = a.CREATE_USER " +
            sqlwhere + ") as table_1";

        String url = request.getContextPath() + "/app/hysyd.do?method=list";

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            QueryJack plus = QueryJackFactory.getInstance().createQueryJack(false);

            // 设置
            plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
            plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
            plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
            plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING, url);
            plus.setParameter(QueryJackFactory.PAGINATION_COUNT, "20");
            plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, pageNO);

            // plus.setParameter(QueryJackFactory.PAGINATION_UPDATEPAGENO, "");
            List resultList = plus.work();

            /**
            if (!resultList.isEmpty()) {
                ModuleManager manager = new ModuleManager(conn);

                for (int i = 0; i < resultList.size(); i++) {
                    String id = (String) ((Map) resultList.get(i)).get("ID");
                    IModule module = manager.getModuleById(id);
                    ((Map) resultList.get(i)).put("module", module);
                }
            }
                        */

            // 获得跳转控制
            Controller controller = plus.getController("form1");

            // 设置调转类型
            controller.setType("input");

            // 显示标签
            Label label = plus.getLabel();

            // 设置显示标签类型
            label.setType("href");

            Object[] result = new Object[4];
            result[0] = resultList;
            result[1] = label;
            result[2] = controller;
            result[3] = pageNO;

            request.setAttribute("result", result);
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("list");
    }

    /**
     * 会议室预定查看
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward hysyd_ck(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        List result_list = new ArrayList();

        //查询日期
        String date = StringTool.checkString(request.getParameter("date"));

        if (date.equals("")) {
            date = DateTrimmer.getYMD();
        } else {
            date = DateTrimmer.formatDateForVarchar(date);
        }

        String id = "1";
        ActionForward forward = null;
        Connection conn = null;

        IUser user = ISystem.getSessionUser(request);

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            HysydManager manager = new HysydManager(conn);
            List list_hys = manager.getHyszyListById(user);

            if ((list_hys != null) && !list_hys.isEmpty()) {
                for (int i = 0; i < list_hys.size(); i++) {
                    Map info = (Map) list_hys.get(i);
                    String hys_id = info.get("HYS_ID").toString();
                    String hys_mc = info.get("HYS_MC").toString();
                    List list_hysyd = manager.getHysydListById(hys_id, date);
                    List temp_list = new ArrayList();
                    temp_list.add(0, info);
                    temp_list.add(1, list_hysyd);
                    result_list.add(temp_list);

                    //temp_list.clear();
                }
            }

            request.setAttribute("hysyd_list_1", result_list);

            request.setAttribute("_date", date);

            request.setAttribute("date", DateTrimmer.getYMD_LBL(date));

            forward = mapping.findForward("list_ydck");
        } catch (Exception ex) {
            forward = mapping.findForward("error");
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return forward;
    }

    /**
     * 会议室预定 审批 列表
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward list_sp(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        Map param = req.getResource();

        String pageNO = StringTool.checkString(param.get("pageNO"));

        String type = StringTool.checkString(request.getParameter("tp"));

        request.setAttribute("tp", type);

        if (type.equals("")) {
            type = "0";
        }

        StringBuffer where = new StringBuffer();
        where.append(" WHERE 1=1 ");

        if (type.equals("0")) {
            where.append(" AND HYSYD_SPZT = " + type);
            where.append(" AND HYSYD_JSSJ >= '" + DateTrimmer.getYMDHMS() +
                "' ");
        } else if (type.equals("1") || type.equals("2")) {
            where.append(" AND HYSYD_SPZT = " + type);
        }

        IUser user = ISystem.getSessionUser(request);

        if (ISystem.matchrole(user, "admin")) {
            //where.append(" AND a.CREATE_USER = " + user.id());
        } else if (ISystem.matchrole(user, "hysadmin")) {
            if (user.igroup() != null) {
                where.append(" AND b.HYS_GSID_NAME = '" +
                    user.igroup().ibranchgroup(0) + "' ");
            }
        }

        // String sql1 = "SELECT COUNT(HYSYD_ID) FROM APP_H_HYSYD ";
        String sql2 =
            "SELECT a.*,b.HYS_MC,b.HYS_ID,c.NAME ,c.ID FROM APP_H_HYSYD a inner " +
            "join APP_H_HYSZY b on a.HYSYD_HYSID = b.HYS_ID inner join ISYS_USER c on c.ID = a.CREATE_USER " +
            where.toString() + " ORDER BY CREATE_DATE DESC";
        String sql1 = "SELECT COUNT(*) FROM (" +
            "SELECT a.*,b.HYS_MC,b.HYS_ID,c.NAME ,c.ID FROM APP_H_HYSYD a inner " +
            "join APP_H_HYSZY b on a.HYSYD_HYSID = b.HYS_ID inner join ISYS_USER c on c.ID = a.CREATE_USER " +
            where.toString() + ") as table_1";

        String url = request.getContextPath() + "/app/hysyd.do?method=list_sp";

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            QueryJack plus = QueryJackFactory.getInstance().createQueryJack(false);

            // 设置
            plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
            plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
            plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
            plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING, url);
            plus.setParameter(QueryJackFactory.PAGINATION_COUNT, "20");
            plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, pageNO);

            // plus.setParameter(QueryJackFactory.PAGINATION_UPDATEPAGENO, "");
            List resultList = plus.work();

            /**
            if (!resultList.isEmpty()) {
                ModuleManager manager = new ModuleManager(conn);

                for (int i = 0; i < resultList.size(); i++) {
                    String id = (String) ((Map) resultList.get(i)).get("ID");
                    IModule module = manager.getModuleById(id);
                    ((Map) resultList.get(i)).put("module", module);
                }
            }
                        */

            // 获得跳转控制
            Controller controller = plus.getController("form1");

            // 设置调转类型
            controller.setType("input");

            // 显示标签
            Label label = plus.getLabel();

            // 设置显示标签类型
            label.setType("href");

            Object[] result = new Object[4];
            result[0] = resultList;
            result[1] = label;
            result[2] = controller;
            result[3] = pageNO;

            request.setAttribute("result", result);
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("list_sp");
    }

    /**
     * 会议室预定 审批
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward hysyd_sp(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        this.view_edit(mapping, form, request, response);

        return mapping.findForward("hysyd_sp");
    }

    /**
     * 新建用户
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward neu(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        HysydManager manager = new HysydManager();

        IUser user = ISystem.getSessionUser(request);

        Map map_user = manager.getUserMap();
        List l_hyszy = manager.getHyszy(user);
        manager.clean();
        request.setAttribute("map_user", map_user);
        request.setAttribute("l_hyszy", l_hyszy);

        return mapping.findForward("neu");
    }

    /**
     * 保存模块定义
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward save(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;
        ActionForward forward = null;

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            XSystemConsole console = new XSystemConsole();
            console.RUN2SAVE(request, conn);
            conn.commit();

            String url = "/hysyd.do?method=list";

            forward = new ActionForward();
            forward.setPath(url);
            forward.setRedirect(true);
        } catch (XSystemConsoleRunException ex) {
            conn.rollback();
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return forward;
    }

    /**
     * 编辑会议室预定信息
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward edit(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        this.view_edit(mapping, form, request, response);

        return mapping.findForward("edit");
    }

    /**
     * 查看会议室预定信息
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward view(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        this.view_edit(mapping, form, request, response);

        return mapping.findForward("view");
    }

    public void view_edit(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {
        String id = StringTool.checkString(request.getParameter("id"));

        HysydManager manager = new HysydManager();

        Map hysyd = manager.gethysydById(id);
        Map map_user = manager.getUserMap();

        List l_hyszy = manager.getHyszy();
        manager.clean();

        request.setAttribute("hysyd", hysyd);
        request.setAttribute("map_user", map_user);
        request.setAttribute("l_hyszy", l_hyszy);
    }

    /**
     * 修改会议室申请信息
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward update(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;
        ActionForward forward = null;

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            XSystemConsole console = new XSystemConsole();
            console.RUN2UPDATE(request, conn);

            HysydManager manager = new HysydManager(conn);

            //manager.sethysydInGroup(id, gid, 0);
            conn.commit();

            String url = "/hysyd.do?method=list";

            forward = new ActionForward();
            forward.setPath(url);
            forward.setRedirect(true);
        } catch (XSystemConsoleRunException ex) {
            conn.rollback();
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return forward;
    }

    /**
     * 审批--会议室申请信息
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward update_sp(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;
        ActionForward forward = null;

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            XSystemConsole console = new XSystemConsole();
            console.RUN2UPDATE(request, conn);

            HysydManager manager = new HysydManager(conn);

            //manager.sethysydInGroup(id, gid, 0);
            conn.commit();

            String url = "/hysyd.do?method=list_sp";

            forward = new ActionForward();
            forward.setPath(url);
            forward.setRedirect(true);
        } catch (XSystemConsoleRunException ex) {
            conn.rollback();
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return forward;
    }

    /**
     * 删除用户（物理删除）
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward delete(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        String ids = StringTool.checkString(request.getParameter("ids"));

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            HysydManager manager = new HysydManager(conn);

            manager.deleteS(ids);

            conn.commit();
        } catch (Exception ex) {
            //ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("delete");
    }
}
